/*封装window、curd
 * @Author: kevin.huang 
 * @Date: 2018-07-22 21:18:18 
 * @Last Modified by: kevin.huang
 * @Last Modified time: 2019-04-20 00:03:19
 * Copyright (c): kevin.huang Released under MIT License
 */
/**
 * 2019-05-23 修复confirm createToolsFn调用bug
 * ****/
(function (global, factory) {
    if (typeof define === 'function' && define.amd  && !window["_all_in_"]) {
        define(['$B', 'plugin', 'panel', 'config'], function (_$B) {
            return factory(global, _$B);
        });
    } else {
        if (!global["$B"]) {
            global["$B"] = {};
        }
        factory(global, global["$B"]);
    }
}(typeof window !== "undefined" ? window : this, function (window, $B) {
    var config = $B.config;
    var document = window.document;
    var $body;

    function _getBody() {
        if (!$body) {
            $body = $(window.document.body).css("position", "relative");
        }
        return $body;
    }
    $.extend($B, {
        /**
         *打开一个窗口
        *arg={
                full:false,//是否满屏，当为true时候，高宽无效
                isTop:false,//是否最顶层打开窗口，默认false
                width:宽度,
                height:高度,
                title:'标题',
                closeType: 'destroy', //关闭类型 hide(隐藏，可重新show)/ destroy 直接从dom中删除
                header:true,//是否显示头部
                draggableHandler:'header',//拖动触发焦点
                iconCls:'',
                position:undefined ,//指定位置 top 、bottom, {top:x ,left : y}
                shadow:true,//是否需要阴影
                draggable:true,//是否可以拖动
                moveProxy:false,//是否代理拖动
                closeable: true,//是否关闭
                maxminable: true,//可变化小大
                collapseable: true,//上下收缩
                content:'内容或者url',
                radius:true,//是否圆角
                closeable: true,//是否可以关闭
                createToolsFn:fn,//自定义创建弹出窗口的按钮
                dataType: 'html',//html/json/iframe
                timeout:0, //自动关闭时间，默认不自动关闭，0表示不自动关闭
                toolbar:工具栏json,优先调用createToolsFn
                mask:true,//是否需要遮罩层
                onClosed:fn, //关闭回调
                onLoaded:fn, //加载完成回调
                onResized:fn //大小发生变化
            }
        返回一个具有close(timeout) api的对象
        ***/
        window: function (args) {
            var _$body, mask = true;
            if (args.isTop) {
                _$body = $(window.top.document.body).css("position", "relative");
            } else {
                _$body = _getBody();
            }
            var _bodyw = parseInt(_$body.outerWidth()),
                _bodyh = parseInt(_$body.outerHeight());
            if(typeof args.width === "string"){
                if(args.width.indexOf("%") > 0){
                    args.width = _bodyw * ( parseInt(args.width.replace("%","")) / 100 );
                }else{
                    args.width = parseInt(args.width.replace("px",""));
                }
            }
            if(typeof args.height === "string"){
                if(args.height.indexOf("%") > 0){
                    args.height = _bodyh * ( parseInt(args.height.replace("%","")) / 100 );
                }else{
                    args.height = parseInt(args.height.replace("px",""));
                }
            }
            if (typeof args.mask !== 'undefined') {
                mask = args.mask;
            }
            if (args.full) {
                args.width = _bodyw;
                args.height = _bodyh;
                mask = false;
                args.draggable = false;
                args.collapseable = false;
                args.maxminable = false;
            }
            if (args.width > _bodyw) {
                args.width = _bodyw;
            }
            if (args.height > _bodyh) {
                args.height = _bodyh;
            }
            var _l = (_bodyw - args.width) / 2;
            var _t = (_bodyh - args.height) / 2;
            _t = _t + (window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0);
            var $mask = _$body.children("#k_window_mask_bg");
            var uuid = this.generateMixed(6);
            if (mask) {
                var maskWidth = parseInt(_$body[0].scrollWidth - 1);
                var maskHeight = parseInt(_$body[0].scrollHeight - 1);
                if ($mask.length === 0) {
                    $mask = $("<div style='z-index:218000000;position:abosulte;top:-100000px;width:" + maskWidth + "px;height:" + maskHeight + "px' for='" + uuid + "' id='k_window_mask_bg'></div>").appendTo(_$body);
                }else{
                    $mask.css({width:maskWidth,height:maskHeight});
                }
                if(args.opacity){
                    $mask.css("opacity",args.opacity);
                }
                if($mask.css("display") === "none"){
                	$mask.css("top", 0).show().attr("for",uuid);
                }
            }
            var $win = $("<div  id='" + uuid + "' style='position:absolute;z-index:2190000000;' class='k_window_main_wrap'></div>");
            var bodyOverflow;
            var posIsPlaintObj ;
            if (args.position) {
                posIsPlaintObj = $.isPlainObject( args.position);
                if(posIsPlaintObj ){
                    $win.css(args.position).appendTo(_$body);
                }else{
                    if (args.position === "bottom") {
                        bodyOverflow = _$body.css("overflow");
                        _$body.css("overflow", "hidden");
                        $win.css({
                            bottom: -1200,
                            right: 0
                        }).appendTo(_$body);
                    } else {
                        $win.css({
                            top: -1200,
                            left: _l
                        }).appendTo(_$body);
                    }
                }
                
            } else {
                $win.css({
                    top: _t,
                    left: _l
                }).appendTo(_$body);
            }
            if (args.full) {
                args.maxminable = false;
            }
            var closeTimer, panel;
            var opts = {
                width: args.width ? args.width : 600,
                height: args.height ? args.height : 300,
                zIndex: 2147483647,
                title: args.title, //标题
                closeType: typeof args.closeType !== 'undefined' ? args.closeType : 'destroy', //关闭类型 hide(隐藏，可重新show)/ destroy 直接从dom中删除
                iconCls: typeof args.iconCls !== 'undefined' ? args.iconCls : 'fa-window-restore', //图标cls，对应icon.css里的class
                iconColor:args.iconColor,
                shadow: typeof args.shadow !== 'undefined' ? args.shadow : true, //是否需要阴影
                radius: typeof args.radius !== 'undefined' ? args.radius : false, //是否圆角                   
                header: typeof args.header !== 'undefined' ? args.header : true, //是否显示头部
                content: args.content, // args.content,
                url: args.url ? args.url:"",
                position: args.position,
                dataType: typeof args.dataType !== 'undefined' ? args.dataType : 'iframe', //当为url请求时，html/json/iframe
                draggableHandler: args.draggableHandler, //拖动触发焦点
                moveProxy: typeof args.moveProxy !== 'undefined' ? args.moveProxy : false, //是否代理拖动
                draggable: typeof args.draggable !== 'undefined' ? args.draggable : true, //是否可以拖动
                closeable: typeof args.closeable !== 'undefined' ? args.closeable : true, //是否关闭
                expandable: false, //可左右收缩                
                maxminable: typeof args.maxminable !== 'undefined' ? args.maxminable : true, //可变化小大
                collapseable: typeof args.collapseable !== 'undefined' ? args.collapseable : true, //上下收缩
                onResized: typeof args.onResized === 'function' ? args.onResized : undefined, //大小变化事件
                onLoaded: typeof args.onLoaded === 'function' ? args.onLoaded : undefined, //加载完成
                onStartDrag: typeof args.onStartDrag === 'function' ? args.onStartDrag : undefined, //开始拖动事件
                onDrag: typeof args.onDrag === 'function' ? args.onDrag : undefined, //拖动中事件
                onStopDrag: typeof args.onStopDrag === 'function' ? args.onStopDrag : undefined, //拖动结束事件
                toolbar: args.toolbar  ? args.toolbar : undefined, //加载完成
                toolbarAlign: args.toolbarAlign  ? args.toolbarAlign : 'center', //工具栏对齐位置
                onClose: function () { //关闭前
                    //console.log("关闭前 >>>>> ");
                    var goClose = true;
                    if (typeof args.onClose === 'function') {
                        goClose = args.onClose();
                    }
                    if (goClose) {
                        clearTimeout(closeTimer);
                    }
                    return goClose;
                },
                onClosed: function () { //关闭后
                    //这里应该判断关闭的窗口 是否关联到 $mask
                    var forId =  $mask.attr("for");
                    var winId = this.attr("id");                   
                    if(forId === winId){
                        $mask.hide();   
                    }             
                    if (typeof args.onClosed === 'function') {
                        args.onClosed();
                    }
                }
            };
            if (args.createToolsFn) {
                opts["createToolsFn"] = args.createToolsFn;
            }
            if(args.fixed){
                opts.expandable = false;
                opts.collapseable = false;
                opts.maxminable = false;
            }
            opts = $.extend({}, config.winDefOpts, opts);
            if(args.timeout && args.timeout < 5){
                opts.closeable = false;
            }
            if (args.isTop) {
                if(window.top.$B){
                    $win.attr("istop",1);
                    panel = new window.top.$B.Panel($win, opts);
                }
            }
            if(!panel){
                panel = new $B.Panel($win, opts);
            }
            if(panel.$header){
                panel.$header.addClass("k_window_header_wrap");
            }            
            if (args.timeout) {
                closeTimer = setTimeout(function () {
                    if (opts.closeType === "destroy") {
                        panel.destroy();
                    } else {
                        panel.close(true);
                    }
                }, args.timeout * 1000);
            }
            if (args.position && !posIsPlaintObj) {
                if (args.position === "bottom") {
                    $win.show();
                    $win.show().animate({
                        bottom: 0
                    }, 300, function () {
                        _$body.css("overflow", bodyOverflow);
                    });
                } else {
                    var fixTop = $(document).scrollTop() + 1;
                    $win.show().animate({
                        top: fixTop
                    }, 300);
                }
            }            
            return panel;
        },
        busyTip:function(args){
            var opts = {
                fixed:true,
                mask:false,
                shadow:false,
                position:'top',
                header:false ,
                isTop:true,
                width:220,
                height:35
            };
            var isOnCloaded = false;
            var mss = $B.config.processing;
            if(arguments.length === 2){
                mss = arguments[0];
                opts.timeout = arguments[1];
            }else{
                if(typeof args === "string") {
                    mss = args;
                }else{
                    if(args.message){
                        mss = args.message;
                        args.message = undefined;
                    }
                    if(args.onClosed){
                        isOnCloaded = true;
                    }
                    $.extend(opts,args);
                }
            }
            opts.onClosed = function(){                
                var queues = window["req_waiting_queues"];
                var obj;
                var newQueue = [],stargetI;
                var i = 0 ,len;
                for( i = 0 ,len = queues.length ; i < len ; ++i){
                    obj = queues[i];
                    if(!obj.jqObj){
                        stargetI = i;
                    }else{
                        newQueue.push(obj);
                    }
                }
                window["req_waiting_queues"] = newQueue;
                for( i = 0 ,len = queues.length ; i < len ; ++i){
                    if(i > stargetI){
                        if(queues[i].jqObj){
                            var newTop = queues[i].jqObj.position().top - 35;
                            if(newTop < 0){
                                newTop = 0;
                            }
                            queues[i].jqObj.animate({top:newTop},50);
                        }                           
                    }
                }
                if(isOnCloaded){
                    args.onClosed();
                }
            };
            opts.content = '<p style="line-height:30px;margin-top:2px;text-align:center;"><i style="color:#FA7900" class="fa fa-spin5 animate-spin"></i><span style="padding-left:12px;color:#FA7900">'+mss +'</span></p>';
            var $win = $B.window(opts);
            var waitingObjs;
            if(opts.isTop){
                waitingObjs =  $(window.top.document.body).children(".k_request_waiting");
            }else{
                waitingObjs = _getBody().children(".k_request_waiting");
            }
            var mvTo = waitingObjs.length * 35;
            if(mvTo > 0){
                $win.jqObj.animate({top:mvTo},350);
            }
            $win.jqObj.addClass("k_request_waiting");            
            if(!window["req_waiting_queues"]){
                window["req_waiting_queues"] = [];
            }
            window["req_waiting_queues"].push($win);
            return $win;
        },
        /**
         *信息提示框
        *args={
                title:'请您确认',
                iconCls:'图标样式',
                message:'提示信息！', //提示信息或者创建html内容的函数
                contentIcon:'内容区域的图标',
                iconColor:'',//内容区域图标颜色
                width: ,//宽度
                height:,//高度         
                timeout:自动消失时间,
                mask://是否需要遮罩,
                toolbar:[],//工具栏的按钮
                createToolsFn://创建工具按钮的函数，优先调用创建函数
        }
        ***/
        message: function (args) {
            var $icon,
                $content,
                position,
                titleIcon = 'fa-mail-alt';
            if (typeof args.message === "function") { //调用创建函数
                $content = args.message();
                if (typeof $content !== "string") {
                    $icon = $content.children(".k_window_content_icon");
                }
            } else if (typeof args === 'string') {
                args  = {message:args};
                if(arguments.length === 2){
                    args.timeout = arguments[1];
                 }
            } 
            $content = $('<div class="k_window_content_wrap clearfix"><div class="k_window_content_icon"></div><p class="k_box_size k_window_content_p">' + args.message + '</p></div>');
            var icon = args.contentIcon ? args.contentIcon : "fa-chat-empty";
            var $i = $("<i class='fa " + icon + "'>\u200B</i>").appendTo($content.children(".k_window_content_icon"));
            if (args.iconColor) {
                $i.css("color", args.iconColor);
            }            
            $icon = $content.children(".k_window_content_icon");
            position = args.position;
            if (args.iconCls) {
                titleIcon = args.iconCls;
            }
            var opts = {
                width: 400,
                height: 200,
                position: position,
                iconColor:args.iconColor,
                title: config.messageTitle, //标题
                iconCls: titleIcon, //图标cls，对应icon.css里的class
                shadow: true, //是否需要阴影
                timeout:  args.timeout ?  args.timeout : 0, //5秒钟后自动关闭
                mask: true, //是否需要遮罩层
                draggableHandler: 'header',
                radius: false, //是否圆角
                header: true, //是否显示头部
                content: $content,
                draggable: true, //是否可以拖动
                closeable: true, //是否关闭
                expandable: false, //可左右收缩
                maxminable: false, //可变化小大
                collapseable: false //上下收缩
            };
            $.extend(opts, args);
            var _opts = $.extend(opts, args);
            var $p = $content.children("p");
            if ($icon) {
                _opts["onResized"] = function () {
                    var h = $p.height() + "px";
                    $icon.children("i").css({
                        "line-height": h,
                        "height": h,
                        "display": "block"
                    });
                };
            }
            var win = this.window(_opts);
            var h = $content.height();
            var iconWidth = $icon ? $icon.outerWidth() : 0;
            var width = $p.outerWidth() + iconWidth;
            var contentWidth = $content.width();
            //实现居中
            var diff = contentWidth - width;
            if (diff > 0) {
                if ($icon && $icon.length > 0) {
                    $icon.css("margin-left", diff / 2);
                } else {
                    $p.css("margin-left", diff / 2);
                }
            }
            var _h;
            var infh = $p.outerHeight();
            if (infh > h) {
                _h = infh - h + 20 + _opts.height;
                // var max_width = contentWidth - iconWidth - 2;
                // $p.css("max-width", max_width + 'px');
                win.resize({
                    height: _h
                });
            } else {
                var paddingtop = parseInt($p.css("padding-top").replace("px"));
                $p.css("margin-top", (h - infh) / 2 - paddingtop / 2);
                if ($icon) {
                    $icon.children("i").css({
                        "line-height": h + "px",
                        "height": h,
                        "display": "block"
                    });
                }
            }
            return win;
        },
        /**
         *成功信息
        *arg={
                message:'提示内容',
                width:,
                height:,
                iconCls:'图标样式',
                timeout:自动消失时间,
                title:'标题',
                mask://是否需要遮罩
        }
        ***/
        success: function (args) {
            var opts = {
                width: 400,
                height: 180,
                title: config.successTitle, //标题
                iconCls: ' fa-check', //
                shadow: true, //是否需要阴影
                timeout: 0, //5秒钟后自动关闭
                mask: true, //是否需要遮罩层
                contentIcon: 'fa-ok-circled',
                iconColor: config.sucessIconColor,
                draggableHandler: 'header'
            };
            if (typeof args === "string") {
                opts.message = args;
                if(arguments.length === 2){
                   opts.timeout = arguments[1];
                }
            } else {
                $.extend(opts, args);
            }
            var win = this.message(opts);
            return win;
        },
        /**
         *警告信息
        *arg={
                message:'提示内容',
                width:,
                height:,
                iconCls:'图标样式',
                timeout:自动消失时间,
                title:'标题',
                mask://是否需要遮罩
        }
        ***/
        alert: function (args) {
            var opts = {
                width: 400,
                height: 150,
                title: config.warnTitle, //标题
                iconCls: 'fa-attention-circled', //图标cls，对应icon.css里的class
                shadow: true, //是否需要阴影
                timeout: 0, //5秒钟后自动关闭
                mask: true, //是否需要遮罩层
                contentIcon: 'fa-attention-1',
                iconColor: config.alertIconColor,
                draggableHandler: 'header'
            };
            if (typeof args === "string") {
                opts.message = args;
                if(arguments.length === 2){
                    opts.timeout = arguments[1];
                 }
            } else {
                $.extend(opts, args);
            }
            var win = this.message(opts);
            return win;
        },
        /**
         * message 错误信息对话框
         * opts = {
                width: 400,
                height: 150,
                title: config.errorTitle, //标题
                iconCls: 'fa-cancel-2', //图标cls，对应icon.css里的class
                shadow: true, //是否需要阴影
                timeout: 0, //5秒钟后自动关闭
                mask: true, //是否需要遮罩层
                contentIcon: 'fa-cancel-circled',
                iconColor: '#F7171C',
                draggableHandler: 'header'
        }
        * ***/
        error: function (args) {
            var opts = {
                width: 400,
                height: 150,
                title: config.errorTitle, //标题
                iconCls: 'fa-attention-1', //图标cls，对应icon.css里的class
                shadow: true, //是否需要阴影
                timeout: 0, //5秒钟后自动关闭
                mask: true, //是否需要遮罩层
                contentIcon: 'fa-cancel-circled',
                iconColor: config.errorIconColor,
                draggableHandler: 'header'
            };
            if (typeof args === "string") {
                opts.message = args;
                if(arguments.length === 2){
                    opts.timeout = arguments[1];
                 }
            } else {
                $.extend(opts, args);
            }
            var win = this.message(opts);
            return win;
        },
        /**
         * 确认提示框
         * args={
                title:'请您确认',
                iconCls:'图标样式',
                message:'提示信息！',
                toolbar:[],//工具栏，如果传入，则不生成默认的按钮
                contentIcon:'内容区域的图标',
                width: ,//宽度
                height:,//高度
                okIcon = "fa-ok-circled",
                okText = "确认",
                noIcon = "fa-ok-circled",
                noText = "取消",
                okFn:fn, //确认回调
                noFn:fn, //否定回调
                contentFn:,//创建内容的函数，返回jq标签
                createToolsFn://创建工具按钮的函数，当不存在toolbar的时候生效，有默认的createToolsFn，this为工具类的jq对象容器
        }
        * ***/
        confirm: function (args) {
            var opts = {
                width: 400,
                height: 150,
                title: config.confirmTitle, //标题
                iconCls: 'fa-question', //图标cls，对应icon.css里的class
                shadow: true, //是否需要阴影
                timeout: 0, //5秒钟后自动关闭
                mask: true, //是否需要遮罩层
                contentIcon: 'fa-help-1',
                draggableHandler: ''
            };           
            var okFn = args.okFn,
                noFn = args.noFn,
                win,
                buttonColor = "#F8F8F8";
            if (args.buttonColor) {
                buttonColor = args.buttonColor;
            }
            delete args.okFn;
            delete args.noFn;
            delete args.buttonColor;
            var okIcon = args.okIcon ? args.okIcon : "fa-ok-circled",
                okText = args.okText ? args.okText : config.buttonOkText,
                noIcon = args.noIcon ? args.noIcon : "fa-reply-all",
                noText = args.noText ? args.noText : config.buttonCancleText;

            delete args.okIcon;
            delete args.okText;
            delete args.noIcon;
            delete args.noText;

            if (typeof args === "string") {
                opts.message = args;
                if(arguments.length === 2){
                    opts.timeout = arguments[1];
                 }
            } else {
                $.extend(opts, args);
            }
            if (typeof args.createToolsFn === "function") {
                opts["createToolsFn"] = args.createToolsFn;
            } else {
                opts["createToolsFn"] = function () {
                    var wrap = this;
                    var tool = $("<div class='k_confirm_buttons_wrap'></div>").appendTo(wrap);
                    var ybtn = $("<button class='yes'><i  class='fa " + okIcon + "'>\u200B</i>" + okText + "</button>").appendTo(tool).click(function () {
                        var goClose = true;
                        if (typeof okFn === "function") {
                            var res = okFn();
                            if (typeof res !== "undefined") {
                                goClose = res;
                            }
                        }
                        if (goClose) {
                            win.close(true);
                        }
                    });
                    var nbtn = $("<button class='no'><i  class='fa " + noIcon + "'>\u200B</i>" + noText + "</button>").appendTo(tool).click(function () {
                        var goClose = true;
                        if (typeof noFn === "function") {
                            var res = noFn();
                            if (typeof res !== "undefined") {
                                goClose = res;
                            }
                        }
                        if (goClose) {
                            win.close(true);
                        }
                    });
                    // setTimeout(function () {
                    //     tool.parent().css("padding-bottom", 0);
                    // }, 10);
                    return tool;
                };
            }
            win = this.message(opts);
            return win;
        }
    });
    /************CURD基本常用API封装*****
    配合datagrid实现的通用表格增删改查
    通用的CURD对象，用于结合datagrid实现表单通用的curd操作api封装**/
    function CURD(tableObj, opts) {
        var gdOpts = $.extend({}, $B.config.curdDatagridOpts, opts);
        this.gdOpts = gdOpts;
        this.opts = $B.config.curdOpts;
        this.id = gdOpts.id;
        this.curWindow = null; //当前打开的window
        this.idField = gdOpts.idField;
        var httpHost = $B.getHttpHost();
        if(gdOpts.url.indexOf(httpHost) >= 0){
            this.url = gdOpts.url;
        }else{
            this.url = httpHost + gdOpts.url;
        }        
        var _url = this.url;
        if (this.url && !/gridid=\w+/.test(this.url)) {
            if (this.url.indexOf("?") > 0) {
                _url = this.url + "&gridid=" + this.id;
            } else {
                _url = this.url + "?gridid=" + this.id;
            }
        }
        gdOpts.url = _url;
        this.dg = new $B.Datagrid(tableObj, gdOpts);
    }
    CURD.prototype = {
        constructor: CURD,
        /**获取datagrid对象**/
        getDataGrid: function () {
            return this.dg;
        },
        updateTitle:function(title){
            this.dg.updateTitle(title);
        },
        /** 打开行内嵌页面
         args= {
                target:'行jQuery对象',
                content:'内容或者url'
                type:'如果是url请求的时候，type=html/iframe',
                onLoaded:function() {如果是url加载，会触发加载完成事件}
          }****/
        openInner: function (args) {
            this.dg.openInner(args);
        },
        /**打开一个操作窗口 一般用于弹出新增、修改窗口
         * args={
                width:500,
                height:200,
                title: '我是测试表头',//标题
                iconCls: 'icon-user',//图标cls，对应icon.css里的class
                shadow:true,//是否需要阴影
                timeout:0,//5秒钟后自动关闭
                mask:true,//是否需要遮罩层
                radius:false,//是否圆角
                header:true,//是否显示头部
                content:'<div><p></p></div>',
                draggableHandler:'header',//拖动触发焦点
                draggable:true,//是否可以拖动
                moveProxy:true,//代理拖动
                closeable: true,//是否关闭
                expandable: false,//可左右收缩
                maxminable:true,//可变化小大
                collapseable: true,//上下收缩
                onResized:function(){//大小变化事件
                    console.log(" onResized  onResized  onResized");
                },
                onClose:function(){ //关闭前
                    console.log("可以关闭了..................");
                    return true;
                },
                onClosed: function () {//关闭后
                    console.log("window关闭了..................");
                }
        }
        isUpdated 是否是打开修改窗口
        ***/
        window: function (args, isUpdated) {
            if($.isPlainObject(args.params)){
                var tmp = [];
                var keys = Object.keys(args.params);
                for(var i = 0 ,len = keys.length ; i < len ;++i){
                    tmp.push(keys[i]+"="+args.params[keys[i]]);
                }
                args.params = tmp.join("&");
            }
            if (isUpdated) {
                var id;
                if (args.rowData) {
                    id = args.rowData[this.idField];
                } else {
                    var chkdatas = this.dg.getCheckedId();
                    if (chkdatas.length === 0) {
                        var msg = typeof args.message === 'undefined' ? $B.config.need2CheckedData : args.message;
                        $B.alert(msg);
                        return;
                    }
                    if (chkdatas.length > 1) {
                        $B.alert($B.config.onlyGetOneData);
                        return;
                    }
                    id = chkdatas[0];
                }
                if (args.params !== undefined && args.params !== '') {
                    args.params = args.params + '&id=' + id;
                } else {
                    args.params = 'id=' + id;
                }
                if (!args["iconCls"]) {
                    args["iconCls"] = "fa-edit";
                }
            }
            var opts = $.extend({}, $B.config.curdWinDefOpts, args);
            var pageName = (opts.pageName && opts.pageName !== "") ? opts.pageName : "form";
            opts.url = this.url.replace(/\?\S+/, '').replace(/list/, $B.config.curdOpts.page_action) + "/" + pageName;
            if (opts.params && opts.params !== '') {
                opts.url = opts.url + "?" + opts.params;
            }
            delete opts.pageName;
            delete opts.params;
            this.curWindow = $B.window(opts);
            return this.curWindow;
        },
        /**
         * 用于$B.window()与curd.window()共用页面时候
         * 便于内部curdObj.add/update能够自动关闭窗口
         * **/
        setOpenWindow: function (win) {
            this.curWindow = win;
        },
        /*** 关闭当前打开的窗口***/
        close: function () {
            if (this.curWindow !== null && this.curWindow.close) {
                this.curWindow.close();                
            }
            this.curWindow = null;
        },
        closeWindow: function () {
            this.close();
        },
        /**新增args=
         {
            data:{}, //提交的参数
            ok:function(data,message){}//成功处理后的回调,
            final:function(res){} //无论成功，失败都回调的事件
        }/
        args = {f1:xx,f2:xx...};
        ***/
        add: function (args,onReturnFn) {
            var url = this.url.replace(/\?\S+/, '').replace(/list/, this.gdOpts.addAction ?  this.gdOpts.addAction: $B.config.curdOpts.add_action);
            this._save(args, url,onReturnFn);
        },
        /**
         * 更新 args={
            data:{},
            ok:function(data,message){},
            final:function(res){}
        }/
        args = {f1:xx,f2:xx...};
        * **/
        update: function (args,onReturnFn) {
            var url = this.url.replace(/\?\S+/, '').replace(/list/, this.gdOpts.updateAction ?  this.gdOpts.updateAction: $B.config.curdOpts.update_action);
            this._save(args, url,onReturnFn);
        },
        /**add / update 的内部调用函数**/
        _save: function (args, url,onReturnFn) {
            var _this = this;
            var opts;
            if (args.data && (typeof args.url !== "undefined" || typeof args.fail === "function" || typeof args.ok === "function" || typeof args.ok === "final")) {
                opts = args;
            } else {
                opts = {
                    waiting:true,
                    data: args,
                    ok: function (message, data,res) {
                        if(typeof onReturnFn === "function"){
                            onReturnFn(res);
                        }
                        _this.close();
                        _this.reload({
                            page: 1
                        });
                    },
                    fail:function(message,res){
                        if(typeof onReturnFn === "function"){
                            onReturnFn(res);
                        }else{
                            $B.error(message);
                        }
                    }
                };
            }
            opts.url = url;
            $B.request(opts);
        },
        /**删除数据 idArray = 需要删除的id数组 
         * args:其他附加的参数
         * ***/
        deleteData: function (idArray,args) {
            this._del({},idArray,args);
        },
        /**删除复选的数据 args={
            message:'提示信息',
            params:{},
            ok:function(data,message){},
            final:function(res){},
            fail:function(){}
            }
            * **/
        delChecked: function (args) {
            var chkdatas = this.dg.getCheckedId();
            this._del(args,chkdatas);
        },
        _del:function(args,idArray,prs){
            if (idArray.length === 0) {
                var msg = ( !args || typeof args.message === 'undefined' )? $B.config.need2CheckForDel : args.message;
                $B.alert(msg);
                return;
            }
            var _this = this;
            $B.confirm({
                message: $B.config.confirmDelete,
                okFn:function(){
                    var deleteAll = _this.dg.getRowCount() === idArray.length;
                    var url = _this.url.replace(/\?\S+/, '').replace(/list/,_this.gdOpts.deleteAction ?  _this.gdOpts.deleteAction: $B.config.curdOpts.del_action);
                    var params = { idList: idArray.join(",") };
                    if(prs){
                        $.extend(params,prs);
                    }
                    if(args && args.params){
                        $.extend(params,args.params);
                    }
                    var opts = {
                        waiting:true,
                        url: url,
                        data: params,
                        ok: function (message, data) {
                            _this.close();
                            if(deleteAll){
                                _this.reload({
                                    page: 1
                                });                                
                            }else{
                                _this.refresh();
                            }
                        }
                    };
                    $B.request(opts);
                }
            });
        },
        /**
         * 获取复选的数据
         * ***/
        getCheckedData: function () {
            return this.dg.getCheckedData();
        },
        /**
         * 获取复选的数据id
         * ***/
        getCheckedId: function () {
            return this.dg.getCheckedId();
        },
        /**获取所有数据**/
        getData: function () {
            return this.dg.getCheckedData(true);
        },
        /**根据参数查询多条数据
         args={
            params:{},
            ok:function(data,message){}
        }
        ****/
        query: function (args) {
        },
        /**根据id查询单条数据
        args={
            id:id
            ok:function(data,message){}
            }
            ***/
        get: function (args) { },
        /**
         * 重新加载
         * args={} 查询参数
         * ****/
        reload: function (args) {
            this.dg.reload(args);
        },
        /**
         * 采用上一次查询的参数刷新当前页
         * **/
        refresh: function () {
            this.dg.refresh();
        }
    };
    $B["CURD"] = CURD;
    /**
     * 获取一个curd实例
     * 请参考curd参数
     * ***/
    $B["getCURD"] = function (tableObj, args) {
        return new CURD(tableObj, args);
    };
    return $B;
}));